/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.testis.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.HashMap;

/**
 *
 * @author nurhat
 */
public class WmiNetworkAdapters {

    //holds index,guid map
    private HashMap<String, String> _interfaceMapByGuid = new HashMap<String, String>();
    private HashMap<String, String> _interfaceMapByPnpInstanceId = new HashMap<String, String>();
    private HashMap<String, String[]> _adapters = new HashMap<String, String[]>();

    public WmiNetworkAdapters() {
        if (OsInfo.isWindows()) {
            populateNetworkAdapters();
        }
    }

    public synchronized String getAdapterIndexByName(String connectionName) {
        if (OsInfo.isWindows()) {
            String[] keys = getAdapters().keySet().toArray(new String[getAdapters().keySet().size()]);
            for (int i = 0; i < keys.length; i++) {
                if (getAdapters().get(keys[i])[0].equals(connectionName)) {
                    return keys[i];
                }
            }
        } else {
            return connectionName;
        }
        return "";
    }

    public synchronized boolean isNetworkAdapterExists(String connectionName) {
        if (OsInfo.isWindows()) {
            String[] keys = getAdapters().keySet().toArray(new String[getAdapters().keySet().size()]);
            for (int i = 0; i < keys.length; i++) {
                if (getAdapters().get(keys[i])[0].equals(connectionName)) {
                    return true;
                }
            }
        } else {
            return true;
        }
        return false;
    }

    public synchronized String getGuidByName(String connectionName) {
        if (OsInfo.isWindows()) {
            String[] keys = getAdapters().keySet().toArray(new String[getAdapters().keySet().size()]);

            for (int i = 0; i < keys.length; i++) {
                String nicIndex = keys[i];
                String nicConName = getAdapters().get(nicIndex)[0];
                String nicPnpInstanceId = getAdapters().get(nicIndex)[1].trim();
                if (nicConName.equals(connectionName)) {
                    if (_interfaceMapByGuid.containsKey(nicIndex)) {
                        return _interfaceMapByGuid.get(nicIndex);
                    }
                    if (!_interfaceMapByPnpInstanceId.containsKey(nicIndex)) {
                        _interfaceMapByPnpInstanceId.put(nicIndex, nicPnpInstanceId);
                    }
                    String guid = getNetworkAdapterGuidByIndex(nicIndex);
                    _interfaceMapByGuid.put(nicIndex, guid);
                    return guid;
                }
            }
        } else {
            return connectionName;
        }
        return null;
    }

    private String runScript(String vbs) {
        String result = "";
        try {
            File file = File.createTempFile("atofwmiScripts", ".vbs");
            file.deleteOnExit();
            FileWriter fw = new java.io.FileWriter(file);


            fw.write(vbs);
            fw.close();
            Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
            BufferedReader input =
                    new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line;
            while ((line = input.readLine()) != null) {
                result += line;
            }
            input.close();
            try {
                file.delete();
                if (file.exists()) {
                    file.deleteOnExit();
                }
            } catch (RuntimeException ex) {
            } catch (Exception ex) {
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public synchronized String getPnpInstanceId(String connectionName) {
        if (OsInfo.isWindows()) {
            String[] keys = getAdapters().keySet().toArray(new String[getAdapters().keySet().size()]);
            for (int i = 0; i < keys.length; i++) {
                String nicIndex = keys[i];
                String nicConName = getAdapters().get(nicIndex)[0];
                String nicPnpInstanceId = getAdapters().get(keys[i])[1].trim();
                if (nicConName.equals(connectionName)) {
                    if (!_interfaceMapByPnpInstanceId.containsKey(nicIndex)) {
                        _interfaceMapByPnpInstanceId.put(nicIndex, nicPnpInstanceId);
                    }
                    return _interfaceMapByPnpInstanceId.get(nicIndex);
                }
            }
        } else {
            return connectionName;
        }
        return null;
    }

    public synchronized String getNetworkAdapterIpByIndex(String index) {
        String vbs =
                "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
                + "Set IPConfigSet  = objWMIService.ExecQuery _ \n"
                + "   (\"Select IPAddress  from Win32_NetworkAdapterConfiguration WHERE Index=" + index + "\",,48) \n"
                + "For Each IPConfig  in IPConfigSet  \n"
                + "    If Not IsNull(IPConfig.IPAddress) Then \n"
                + "        For i=LBound(IPConfig.IPAddress) to UBound(IPConfig.IPAddress)\n"
                + "                WScript.Echo IPConfig.IPAddress(i)& \"\t\"\n"
                + "        Next\n"
                + "    End If\n"
                + "Next \n";
        String result = runScript(vbs);

        String[] ips = result.split("\t");
        if (ips.length > 0) {
            return ips[0];
        }
        return "";
    }

    public synchronized String getNetworkAdapterDnsByIndex(String index) {
        String vbs =
                "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
                + "Set DNSServerSearchOrderConfigSet  = objWMIService.ExecQuery _ \n"
                + "   (\"Select DNSServerSearchOrder  from Win32_NetworkAdapterConfiguration WHERE Index=" + index + "\",,48) \n"
                + "For Each DNSServerSearchOrderConfig  in DNSServerSearchOrderConfigSet  \n"
                + "    If Not IsNull(DNSServerSearchOrderConfig.DNSServerSearchOrder) Then \n"
                + "        For i=LBound(DNSServerSearchOrderConfig.DNSServerSearchOrder) to UBound(DNSServerSearchOrderConfig.DNSServerSearchOrder)\n"
                + "                WScript.Echo DNSServerSearchOrderConfig.DNSServerSearchOrder(i)& \"\t\"\n"
                + "        Next\n"
                + "    End If\n"
                + "Next \n";
        String result = runScript(vbs);

        String[] dns = result.split("\t");
        if (dns.length > 0) {
            return dns[0];
        }
        return "";
    }

    public synchronized String getNetworkAdapterGateWayByIndex(String index) {

        String vbs = "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
                + "Set GateWayConfigSet  = objWMIService.ExecQuery _ \n"
                + "   (\"Select DefaultIPGateway  from Win32_NetworkAdapterConfiguration WHERE Index=" + index + "\",,48) \n"
                + "For Each GateWayConfig  in GateWayConfigSet  \n"
                + "    If Not IsNull(GateWayConfig.DefaultIPGateway) Then \n"
                + "        For i=LBound(GateWayConfig.DefaultIPGateway) to UBound(GateWayConfig.DefaultIPGateway)\n"
                + "                WScript.Echo GateWayConfig.DefaultIPGateway(i)& \"\t\"\n"
                + "        Next\n"
                + "    End If\n"
                + "Next \n";
        String result = runScript(vbs);
        String[] gateways = result.split("\t");
        if (gateways.length > 0) {
            return gateways[0];
        }
        return "";
    }

    public synchronized String getNetworkAdapterSubnetByIndex(String index) {

        String vbs = "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
                + "Set IPSubnetConfigSet  = objWMIService.ExecQuery _ \n"
                + "   (\"Select IPSubnet  from Win32_NetworkAdapterConfiguration WHERE Index=" + index + "\",,48) \n"
                + "For Each IPSubnetConfig  in IPSubnetConfigSet  \n"
                + "    If Not IsNull(IPSubnetConfig.IPSubnet) Then \n"
                + "        For i=LBound(IPSubnetConfig.IPSubnet) to UBound(IPSubnetConfig.IPSubnet)\n"
                + "                WScript.Echo IPSubnetConfig.IPSubnet(i)& \"\t\"\n"
                + "        Next\n"
                + "    End If\n"
                + "Next \n";
        String result = runScript(vbs);
        String[] subnets = result.split("\t");
        if (subnets.length > 0) {
            return subnets[0];
        }
        return "";
    }

    public synchronized String getNetworkAdapterGuidByIndex(String index) {
        String vbs =
                "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
                + "Set colItems = objWMIService.ExecQuery _ \n"
                + "   (\"Select SettingID from Win32_NetworkAdapterConfiguration WHERE Index=" + index + "\",,48) \n"
                + "For Each objItem in colItems \n"
                + "    Wscript.Echo objItem.SettingID  \n"
                + "Next \n";
        String result = runScript(vbs);

        return result;
    }
    public synchronized String getNetworkAdapterMacAddressByIndex(String index) {
        String vbs =
                "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
                + "Set colItems = objWMIService.ExecQuery _ \n"
                + "   (\"Select MACAddress from Win32_NetworkAdapterConfiguration WHERE Index=" + index + "\",,48) \n"
                + "For Each objItem in colItems \n"
                + "    Wscript.Echo objItem.MACAddress \n"
                + "Next \n";
        String result = runScript(vbs);

        return result;
    }
    private synchronized void populateNetworkAdapters() {
        String vbs =
                "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
                + "Set colItems = objWMIService.ExecQuery _ \n"
                + "   (\"Select * from Win32_NetworkAdapter WHERE NetConnectionID IS NOT NULL\",,48) \n"
                + "For Each objItem in colItems \n"
                + "    Wscript.Echo objItem.Index & \"\b\" & objItem.NetConnectionID & \"\b\" &  objItem.PNPDeviceID & \"\t\"  \n"
                + "Next \n";
        String result = runScript(vbs);

        getAdapters().clear();
        String[] nics = result.split("\t");

        for (int i = 0; i < nics.length; i++) {
            String[] mapEntry = nics[i].split("\b");
            String[] value = new String[2];
            value[0] = mapEntry[1];
            value[1] = mapEntry[2];
            getAdapters().put(mapEntry[0], value);
        }
    }

    /**
     * @return the _adapters
     */
    public HashMap<String, String[]> getAdapters() {
        return _adapters;
    }
}
